package com.youthburin.rmp.shiro;

import java.util.Map;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.youthburin.rmp.domain.UserInfo;
import com.youthburin.rmp.services.UserInfoService;

public class MyShiroDbRealm extends AuthorizingRealm {
	private final Logger logger = LoggerFactory.getLogger(MyShiroDbRealm.class);
	@Autowired
	private UserInfoService userService;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		UserInfo userInfo = (UserInfo) principals.getPrimaryPrincipal();

		Map<String, Set<String>> roleAndPermission = userService.getRoleAndPermission(userInfo.getCode());

		SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
		simpleAuthorizationInfo.setRoles(roleAndPermission.get("roles"));
		simpleAuthorizationInfo.setStringPermissions(roleAndPermission.get("permissions"));

		return simpleAuthorizationInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;

		String userCode = usernamePasswordToken.getUsername();
		if (logger.isInfoEnabled()) {
			logger.info(userCode + " from " + usernamePasswordToken.getHost() + " try to login...");
		}

		UserInfo userInfo = userService.getSystemUserInfo(userCode);
		String password = userService.getPassword(userCode);

		SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(userInfo, password, getName());
		authenticationInfo.setCredentialsSalt(ByteSource.Util.bytes(userCode));

		return authenticationInfo;
	}
}
